package com.shijun.im.activity.interactor.impl;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadTask;
import com.alibaba.sdk.android.media.utils.FailReason;
import com.shijun.im.activity.RegistActivity;
import com.shijun.im.activity.interactor.RegistInteractor;
import com.shijun.im.application.MyAppLication;
import com.shijun.im.bean.RequestTokenBean;
import com.shijun.im.bean.SimplRequestBean;
import com.shijun.im.config.HttpResultCodeAPI;
import com.shijun.im.http.APIInterface;
import com.shijun.im.http.RetrofitService;
import com.shijun.im.service.IMService;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by zhushijun on 2017/10/19 0019.
 */

public class RegistInteractorImpl implements RegistInteractor {
    private APIInterface serviceUpLoad, serviceRegister;
    private Context context;
    private Uri tempUri = null;
    private Map<String, String> imServiceMap;
    private OnRegistFinishedListener listener;
    private boolean isSetAvatar = false;
    public RegistInteractorImpl() {
    }

    public RegistInteractorImpl(Context context) {
        this.context = context;
    }

    @Override
    public void registInput(Map<String, String> userInfo, OnRegistInputListener listener) {
        String username = userInfo.get("username");
        String password = userInfo.get("password");
        String passwordcommit = userInfo.get("passwordcommit");
        String phone = userInfo.get("phone");
        String email = userInfo.get("email");
        String address = userInfo.get("address");
        if (username == null || "".equals(username)) {
            listener.onInputError(RegistInteractor.REGIST_USERNAMEERROR, "用户名不能为空！");
            return;
        }
        if (username.length() > 16 || username.length() < 4) {
            listener.onInputError(RegistInteractor.REGIST_USERNAMEERROR, "用户名长度必须[4-16]之间！");
            return;
        }
        if (password == null || "".equals(password)) {
            listener.onInputError(RegistInteractor.REGIST_PASSWORDERROR, "密码不能为空！");
            return;
        }
        if (password.length() > 16 || password.length() < 6) {
            listener.onInputError(RegistInteractor.REGIST_PASSWORDERROR, "密码长度必须[6-16]之间！");
            return;
        }
        if (passwordcommit == null || "".equals(passwordcommit)) {
            listener.onInputError(RegistInteractor.REGIST_PASSWORDCOMMITERROR, "请再次输入密码");
            return;
        }
        if (!password.equals(passwordcommit)) {
            listener.onInputError(RegistInteractor.REGIST_PASSWORDCOMMITERROR, "两次密码输入不一致");
            return;
        }

        if (phone != null && !"".equals(phone) && validatePhoneNum(phone)) {
            listener.onInputError(RegistInteractor.REGIST_PHONEERROR, "手机号格式有误！");
            return;
        }

        if (email != null && !"".equals(email) && validateEmail(email)) {
            listener.onInputError(RegistInteractor.REGIST_EMAILERROR, "邮箱格式有误！");
            return;
        }

        if (address != null && !"".equals(address) && address.length() > 20) {
            listener.onInputError(RegistInteractor.REGIST_EMAILERROR, "地址长度必须不能大于20！");
            return;
        }

        listener.onInputSuccess();
    }

    @Override
    public void registCommit(Context context, final Map<String, String> userInfo, final OnRegistFinishedListener listener) {
        this.listener = listener;
        imServiceMap = new HashMap<String, String>();
        String username = userInfo.get("username");
        String password = userInfo.get("password");
        String email = userInfo.get("email");
        String phone = userInfo.get("phone");
        String address = userInfo.get("address");
        String avatar = userInfo.get("avatar");
        Log.i("shijunTAG", "userName:" + username);
        Log.i("shijunTAG", "password:" + password);
        Log.i("shijunTAG", "password:" + userInfo);
        if (username != null && !"".equals(username)) {
            imServiceMap.put("userName", username);

        }
        if (password != null && !"".equals(password)) {
            imServiceMap.put("password", password);

        }
        if (email != null && !"".equals(email)) {
            imServiceMap.put("email", email);
        }
        if (phone != null && !"".equals(phone)) {
            imServiceMap.put("phone", phone);
        }
        if (address != null && !"".equals(address)) {
            imServiceMap.put("address", address);
        }
        if (avatar != null && !"".equals(avatar)) {
            imServiceMap.put("avatar", avatar);
        }
        if(isSetAvatar){
            upLoadingAvatar();
        }else{
            doRegist();
        }

    }

    @Override
    public void upLoadingAvatar() {
        serviceUpLoad = new RetrofitService<RequestTokenBean>(RequestTokenBean.class).getRectService();
        Call<RequestTokenBean> model = serviceUpLoad.repo("shijun", "123456");
        Log.i("shijunTAG", "获取Token:");
        model.enqueue(new Callback<RequestTokenBean>() {
            @Override
            public void onResponse(Call<RequestTokenBean> call, Response<RequestTokenBean> response) {
                Log.i("shijunTAG", "Token:" + response.toString());
                Log.i("shijunTAG", "Token:" + response.body().toString());

                String token = response.body().getToken(); //从开发者服务端请求获取的凭证token
                File f = new File(Environment.getExternalStorageDirectory() +RegistActivity.IMAGE_FILE_PATH, RegistActivity.IMAGE_CROP_TEMP_NAME);
                doUpLoadImage(f, token);
            }

            @Override
            public void onFailure(Call<RequestTokenBean> call, Throwable t) {
                if(t!=null)
                    Log.i("shijunTAG", "Token:" + t.getMessage().toString());
                listener.onRegistError();
            }
        });
    }

    private boolean validatePhoneNum(String phoneNum) {
        Pattern pattern = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[01236789]))\\d{8}$");
        Matcher matcher = pattern.matcher(phoneNum);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    private boolean validateEmail(String email) {
        final String pattern1 = "^([a-z0-9A-Z]+[-|//.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?//.)+[a-zA-Z]{2,}$";
        final Pattern pattern = Pattern.compile(pattern1);
        final Matcher mat = pattern.matcher(email);
        if (!mat.find()) {
            return false;
        }
        return true;
    }

    private void doRegist(){
        serviceRegister = new RetrofitService<SimplRequestBean>(SimplRequestBean.class).getRectService();
        Call<SimplRequestBean> model = serviceRegister.register(imServiceMap);

        model.enqueue(new Callback<SimplRequestBean>() {
            @Override
            public void onResponse(Call<SimplRequestBean> call, Response<SimplRequestBean> response) {
                SimplRequestBean result = response.body();
                Log.i("shijunTAG", "result:" + result.toString());
                if (HttpResultCodeAPI.SUCCESS == result.getResultCode()) {
                    listener.onRegistSuccess();
                } else {
                    listener.onRegistError();
                }
            }

            @Override
            public void onFailure(Call<SimplRequestBean> call, Throwable t) {
                Log.i("shijunTAG", "result:" + t.getMessage());
                listener.onRegistError();
            }
        });
    }

    private void doUpLoadImage(File file, String token) {
        ((MyAppLication) ((Activity) context).getApplication()).getWantuService().upload(file, new UploadListener() {
            @Override
            public void onUploading(UploadTask uploadTask) {
                Log.i("shijunTAG", "getCurrent:" + uploadTask.getCurrent());
            }

            @Override
            public void onUploadFailed(UploadTask uploadTask, FailReason failReason) {
                Log.i("shijunTAG", "doUpLoadImage:" + failReason.getMessage().toString());
                listener.onRegistError();
            }

            @Override
            public void onUploadComplete(UploadTask uploadTask) {
                String avatar = uploadTask.getResult().url;
                Log.i("shijunTAG", "doUpLoadImage:" + avatar);
                if (avatar != null && !"".equals(avatar)) {
                    imServiceMap.put("avatar", avatar);
                }
                doRegist();
            }

            @Override
            public void onUploadCancelled(UploadTask uploadTask) {

            }
        }, token);
    }

    /**
     * 裁剪原始的图片
     */
    @Override
    public void cropRawPhoto(Uri uri, int output_X, int output_Y) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("scale", true);
        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", RegistActivity.output_X);
        intent.putExtra("outputY", RegistActivity.output_Y);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        ((Activity) context).startActivityForResult(intent, RegistActivity.CODE_RESULT_REQUEST);
    }

    // 从本地相册选取图片作为头像
    @Override
    public void getLocationImage() {
        Intent intentFromGallery = new Intent();
        intentFromGallery.setType("image/*");//选择图片
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        ((Activity) context).startActivityForResult(intentFromGallery, RegistActivity.CODE_GALLERY_REQUEST);
    }

    // 启动手机相机拍摄照片作为头像
    @Override
    public void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        ((Activity) context).startActivityForResult(intent, RegistActivity.CODE_CAMERA_REQUEST);
    }

    /**
     * 提取保存裁剪之后的图片数据，并设置头像部分的View
     */
    @Override
    public void setImageToHeadView(Uri uri, OnAvatarListener listener) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(tempUri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (bitmap != null) {
            listener.onShowAvatar(bitmap);

            //在根目录下面的ShijunIM文件夹下 创建avatar.jpg文件
            File f = new File(Environment.getExternalStorageDirectory() +RegistActivity.IMAGE_FILE_PATH, RegistActivity.IMAGE_CROP_TEMP_NAME);
            FileOutputStream out = null;
            try {   //打开输出流 将图片数据填入文件中
                out = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
                isSetAvatar = true;
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    @Override
    public boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    public Uri getTempUri() {

        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            //先清空缓存文件夹
            File foder = new File(Environment.getExternalStorageDirectory()+"/DCIM/shijunIM/");
            if (!foder.exists()) {
                foder.mkdirs();
            }else {
                if (foder.isDirectory()) {
                    File[] files = foder.listFiles();
                    if (files!=null && files.length>0){
                        for (int i = 0; i < files.length; i++) {
                            files[i].delete();
                        }
                    }
                }
            }

            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            String filename = timeStampFormat.format(new Date());
            File tempFile = new File(Environment.getExternalStorageDirectory()+"/DCIM/shijunIM/",filename+".jpg");
            if (android.os.Build.VERSION.SDK_INT < 24) {
                // 从文件中创建uri
                tempUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                //检查是否有存储权限，以免崩溃
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    Toast.makeText(context,"请开启存储权限",Toast.LENGTH_SHORT).show();
                    return null;
                }
                tempUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            }return tempUri;
        }else{
            return null;
        }
    }
}
